<template>
  <div class="table-search-page">
    <a-card class="g-mt-10" :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" :form="form" :selfUpdate="true">
          <a-row :gutter="12">
            <a-col :md="12" :lg="6" :sm="12" style="padding: 0 4px;">
              <a-form-item label="登记时间">
                <a-range-picker v-model="tegistrationTime" style="width: 100%;" @change="timeSearchChange">
                  <a-icon slot="suffixIcon" type="calendar"/>
                </a-range-picker>
              </a-form-item>
            </a-col>
             
            <a-col :md="2" :lg="4" :sm="12">
              <div class="table-page-search-submitButtons g-flex" style="margin-bottom: 4px;">
                <!-- <a-icon :type="advanced ? 'up' : 'down'" @click="advanced=!advanced" style="margin-right: 15px;"/> -->
                <a-button type="primary" @click="clickSearch">查询</a-button>
                <a-button style="margin-left: 8px" @click="clickReset">重置</a-button>
              </div>
            </a-col>
          </a-row>
       
        </a-form>
      </div>
    </a-card>
 
    <a-card :bordered="false" class="settlement-form-table">
       <super-table 
          ref="table"
          :rowKey="(record,index)=> index"
          :columns="columns"
          :data="loadData"
          :bordered="false"
          style="margin-top:10px;"
        >
          <!--序号-->
          <template slot="index" slot-scope="text,record,index">
            <span>{{(queryParam.pageNum-1)*pagination.pageSize+(index+1)}}</span>
          </template>
          <!--客户卡号-->
          <template slot="cardNo" slot-scope="text,record">
            <div class="g-color g-f-14" style="cursor: pointer;" @click="toCustomerDetails(text,record)">{{ text }}</div>
          </template>
          <template slot="action" slot-scope="text,record">
            <div  style="margin:0 auto">
              <a-button style="padding:0;" type="link" @click="openDrawer(record)" >明细</a-button> 
            </div>
          </template>
        </super-table>
      

    </a-card>

    <!--项目抽屉--弹窗-->
    <item-drawer ref="itemDrawer" :row_record="current_row_record" />

    
  </div>
</template>

<script>
import { AllHisUser, CustomerLevel, CustomerState } from '@/api/customer/customer'
import { CustomerFeedback } from '@/api/modular/main/customer/customerReturnVisit' 
import { testingAccountNumber,beginReport,settleHtmlSettle_1,getReportFormDeptAll, paymentMethodReport, getReportFormRepostAll} from '@/api/modular/main/customer/cashier'
import { SuperTable, upTime } from '@/components'
import itemDrawer from '@/views/Cashier/settlementStatement/itemDrawer.vue'
import moment from 'moment'
import { axios } from '@/utils/request'
import {Timeline} from 'ant-design-vue' 
 
export default {
  components: {
    SuperTable,
    upTime,
    itemDrawer,
    [Timeline.Item.name]: Timeline.Item
  },
  computed: {
    
  },
  data() {
    return {
      dataSource:[],
      loadData: parameter => {
        this.queryParam.pageNum = parameter.pageNum
        this.queryParam.pageSize = parameter.pageSize
        return paymentMethodReport(this.queryParam).then(res => {
          this.loading = false//关闭加载 
          this.dataSource = [...res.rows]
          let newData = Object.assign({},res)
          return newData
        })
      },
      form: this.$form.createForm(this),
      customerState: [],//客户状态
      customerLevel: [],//客户等级
      advanced: false, // 高级搜索 展开/关闭
      disabled: true, //是否禁用新增按钮
      current_row_record: {},
      columns: [ 
        { title: '日期', align:'center', dataIndex: 'days', width: 140, ellipsis: true }, 
        { title: '总额', align:'center', dataIndex: 'resultSaleAmt', width: 140, ellipsis: true }, 
        { title: '现金', align:'center', dataIndex: 'xj', width: 140, ellipsis: true }, 
        { title: '刷卡', align:'center', dataIndex: 'sk', width: 140, ellipsis: true }, 
        { title: '转账', align:'center', dataIndex: 'zz', width: 140, ellipsis: true }, 

        { title: '操作', align:'center', scopedSlots: { customRender: 'action' }, align:'center', width: 80 }
        
      ],
      data: [],
      pagination: {
        current: 1,//当前页
        pageSize: 10,//当前页数
        total: 0,//总条数
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '30'],//这里注意只能是字符串，不能是数字
        showTotal: total => `共有 ${total} 条数据`//分页中显示总的数据
      },
      // 查询参数
      queryParam: {
        pageNum: 1,//第几页
        pageSize: 10,//每页中显示数据的条数
        current:1,
        type: 1,
        begintime: undefined,
        endtime: undefined,
        chargeType:1
      },
      loading: true, //加载状态,
      current_row_index: '',
      customerFeedback: {},
      allHisUser: {}, //回访人对象
      currentActiveKey: 1,
      
      // 日结显示
      settlementVisible: false,
      // 时间
      gettime:'',
      // 图片
      imgVisible: false,
      imgSrc:'',

      settlementLoading: false,
      settlementLoadingText: '开始结算中',  // 日结loading
      indicator: <a-icon type="loading" spin />,
      loadingTextArr: [],
      watchBool:false,
      tegistrationTime: []
    }
  },
  created() {
    this.getBaseFormInfo()
  },
  watch:{
    watchBool(){
      this.queryParam.pageNum = 1
      this.queryParam.pageSize = 10
      this.queryParam.current = 1
      this.queryParam = Object.assign({},this.queryParam)
    }
  },
  methods: { 
    timeSearchChange(date,day){
      console.log(day)
      this.tegistrationTime = day
    },
    // tabs 切换
    tabsChange(tab,index){
      this.queryParam.pageNum = 1
      this.queryParam.pageSize = 10
      this.queryParam.current = 1
      this.queryParam = Object.assign({},this.queryParam)

      console.log(tab)
      if(tab == 1){
        this.loadData = (parameter) => {
          this.queryParam.pageNum = parameter.pageNum
          this.queryParam.pageSize = parameter.pageSize
          return getReportFormDeptAll(this.queryParam).then(res => {
            this.loading = false//关闭加载 
            this.dataSource = [...res.rows]
            let newData = Object.assign({},res)
            return newData
          }) 
        }
      }else if(tab == 2){
        // 支付方式 
        this.loadData = (parameter) => { 
          this.queryParam.pageNum = parameter.pageNum
          this.queryParam.pageSize = parameter.pageSize
          return paymentMethodReport(this.queryParam).then(res => {
            this.loading = false//关闭加载 
            this.dataSource = [...res.rows]
            let newData = Object.assign({},res)
            return newData
          })
        }
      }else if(tab == 3){
        // 日结总表
        this.loadData = (parameter) => { 
          this.queryParam.pageNum = parameter.pageNum
          this.queryParam.pageSize = parameter.pageSize
          return getReportFormRepostAll(this.queryParam).then(res => {
            this.loading = false//关闭加载 
            this.dataSource = [...res.rows]
            let newData = Object.assign({},res)
            return newData
          })
        }
      }
      this.$nextTick(() => {
        this.$refs.table.refresh()
      })
      
    },
    // 新增日结点击 确认
    handleOk(e) {  
      this.loadingTextArr = ['正在结算中...']
       
      let sendData = {
        settleType: 1
      }
      
      this.settlementLoading = true
      testingAccountNumber().then(res => {
        console.log(res)
        if(res.code === -1){
          beginReport().then(result => {
            console.log(result) 
            if(result.code == 0){
              settleHtmlSettle_1(sendData).then(elem => { 
                if(elem.code == 0){
                  this.loadingTextArr.push(elem.msg)
                  this.settlementLoadingText = elem.msg 
                  this.loadingFunc(elem.step) 
                }else{
                  this.$message.error(elem.message)
                }
              })
            }
          })

        }else if(res.code === 0){
          settleHtmlSettle_1(sendData).then(elem => {
            console.log(elem)
              if(elem.code == 0){
                this.loadingTextArr.push(elem.msg)
                this.settlementLoadingText = elem.msg 
                this.loadingFunc(elem.step) 
              }else{
                this.$message.error(elem.message)
              }
          })
        }else if(res.code === 1){
          this.settlementLoading = false 
          this.$message.error(res.msg)
          this.settlementVisible = false;   
        }
      })

    },
    loadingFunc(url,type = 1){ 
      let sendData = {
        settleType: type
      } 
      let thisOldTime = new Date().getTime()
      axios({
        url: url + '?settleType=1',
        methods: 'get',
        data: sendData,

      }).then(elem => {

        let timeData = ((new Date().getTime()) - thisOldTime) / 1000 

        if(timeData < 2){ 
          let timeoutClear = setInterval(() => {
            timeData = timeData + 1 
            if(timeData > 2){ 
              clearInterval(timeoutClear)
              this.loadingTextArr.push(elem.msg)
              this.settlementLoadingText = elem.msg
              if(elem.step != ''){
                return this.loadingFunc(`${elem.step}`)
              }else{
                this.settlementLoading = false 
                this.imgVisible = true 
                this.settlementVisible = false;  
                this.$message.success(elem.message)
                this.imgSrc = `${elem.row}`  
              }
            }
          }, 1000); 
        }

       
      })
    },
     

    // 获取当前的日期
    getCurrentTime() {
      //获取当前时间并打印
      var _this = this;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth()+1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();
      _this.gettime = yy+'/'+mm+'/'+dd+' '+hh+':'+mf+':'+ss; 
    },




    checkPattern(str) {
      const pattern = new RegExp('[\u4E00-\u9FA5]+')
      if (pattern.test(str)) {
        return true
      }
      return false
    },
    //下拉框搜索查找
    select_search_consultMan(value) {
      this.form.setFieldsValue({
        consultMan: value
      })
    },
    //下拉框搜索查找
    select_search_developer(value) {
      this.form.setFieldsValue({
        developer: value
      })
    },

    moment,
    toCountDown(time) {
      //1000代表1秒，1000*60代表60分钟
      return Date.now() + parseInt(time) * 1000
    },
    minutesToSeconds(time) {
      return parseInt(time)
    },
    changeRadio(e){
      const value =e.target.value
      this.queryParam.chargeType = value
      this.$refs.table.loadData()
    },
    //点击查询-高级搜索
    clickSearch() { 
      this.watchBool = !this.watchBool
      this.queryParam.pageNum = 1
      this.queryParam.pageSize = 10
      this.queryParam.current = 1

      let form_values = {}
      const time = this.tegistrationTime
      console.log(time)
      if (time && time.length > 0 && time[0] != '' && time[1] !='') {
        form_values.settleDate = moment(time[0]).format('YYYY-MM-DD')
        form_values.endTime = moment(time[1]).format('YYYY-MM-DD') 
      }else{
        form_values.settleDate = undefined
        form_values.endTime = undefined
      } 
      this.queryParam = Object.assign(this.queryParam,form_values)
      this.$nextTick(() => {
        this.$refs.table.loadData()
      })
      
    },
    clickReset() {
      let form_values = {}
      this.tegistrationTime = [] 
      form_values.settleDate = undefined
      form_values.endTime = undefined 
      this.queryParam = Object.assign(this.queryParam,form_values)  
    },
     
    openDrawer(record){
      this.current_row_record=record
      this.$refs.itemDrawer.show()
    },
     
    //点击查看客户详情
    toCustomerDetails(text, record) {
      // console.log(record)
      this.$router.push({
        path: 'customer_details', query: {
          id: record.customerId,
          card_no: record.cardNo,
          customerName:record.customerName
        }
      })
    },
    
    
    // 表格行点击事件
    clickRow(record, index) {
      return {
        on: {
          click: () => {
            // console.log('点击当前行',record)
            this.disabled = false
            this.current_row_index = index
            this.current_row_record = record
          }
        }
      }
    },
    //获取表单相关接口
    getBaseFormInfo() {
      CustomerFeedback().then(res => {
        // console.log('回访相关表单接口',res)
        this.customerFeedback = res
      })
      AllHisUser().then(res => {

        this.allHisUser = res
        // this.allHisUser.userList=transformKey(this.allHisUser.userList,'id','value')
        // console.log('全员员工接口',this.allHisUser.userList)

      })
      CustomerLevel().then(res => {
        this.customerLevel = res
      })
      CustomerState().then(res => {
        this.customerState = res
      })
    }
  }

}
</script>

<style lang="less" scoped>

.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
  margin-bottom: 2px;
}

.currentRowClass {
  background: #e6f7ff;
}

/deep/ .ant-tabs-bar {
  // border-bottom: none;
  border-bottom: 1px solid #e8e8e8;
}

/deep/ .ant-badge-count, .ant-badge-dot, .ant-badge .ant-scroll-number-custom-component {
  right: -10px;
}
/deep/ .model-loading-box{
  .ant-modal-body{
    position: relative;
  }
}
.settlement-loading-style{
  font-weight: bold;
  color: #3399ff;
  position: absolute;
  top: 80px;
  width: 100%;
  margin-left: -24px;
  font-size: 18px;
  background-color: #fff;
  min-height: 146px;
  z-index: 10;

  .settlement-loading-style-timeline{
    width: 300px;
    margin: 0 auto;
    .ant-timeline-item-content{
      font-size: 17px;
      line-height: 26px;
      margin-left: 25px;
    }
  }
}
/deep/ .settlement-form-table{ 
  .ant-table-small.ant-table-bordered .ant-table-fixed-right{
    border-left: 0 !important;
    border-right: 0 !important;
  }
}

</style>